import { useState, useRef, useEffect } from 'react'
import { StorageService } from '../services/storage'

interface Song {
  id: string
  title: string
  artist: string
  url: string
  description?: string
}

export function MusicPlayer() {
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentSong, setCurrentSong] = useState(0)
  const [volume, setVolume] = useState(0.5)
  const [isVisible, setIsVisible] = useState(true)
  const [showPlaylist, setShowPlaylist] = useState(false)
  const [playlist, setPlaylist] = useState<Song[]>([])
  const audioRef = useRef<HTMLAudioElement>(null)

  // 加载播放列表
  useEffect(() => {
    const savedPlaylist = StorageService.getMusicPlaylist()
    if (savedPlaylist.length > 0) {
      setPlaylist(savedPlaylist)
    } else {
      // 默认播放列表
      const defaultPlaylist: Song[] = [
        {
          id: "1",
          title: "我们的歌",
          artist: "特别的回忆",
          url: "/music/our-song.mp3",
          description: "第一次听到这首歌时的美好回忆"
        },
        {
          id: "2", 
          title: "相遇的那天",
          artist: "美好时光",
          url: "/music/meeting-day.mp3",
          description: "那个改变一切的美好日子"
        },
        {
          id: "3",
          title: "爱的旋律",
          artist: "甜蜜回忆", 
          url: "/music/love-melody.mp3",
          description: "属于我们两个人的专属旋律"
        }
      ]
      setPlaylist(defaultPlaylist)
      StorageService.saveMusicPlaylist(defaultPlaylist)
    }
  }, [])

  const togglePlay = () => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause()
      } else {
        audioRef.current.play()
      }
      setIsPlaying(!isPlaying)
    }
  }

  const nextSong = () => {
    setCurrentSong((prev) => (prev + 1) % playlist.length)
  }

  const prevSong = () => {
    setCurrentSong((prev) => (prev - 1 + playlist.length) % playlist.length)
  }

  const selectSong = (index: number) => {
    setCurrentSong(index)
    setShowPlaylist(false)
  }

  const removeSong = (songId: string) => {
    const updatedPlaylist = playlist.filter(song => song.id !== songId)
    setPlaylist(updatedPlaylist)
    StorageService.saveMusicPlaylist(updatedPlaylist)
    
    if (currentSong >= updatedPlaylist.length) {
      setCurrentSong(0)
    }
  }

  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume
    }
  }, [volume])

  useEffect(() => {
    if (audioRef.current && playlist.length > 0) {
      audioRef.current.src = playlist[currentSong]?.url || ''
      if (isPlaying) {
        audioRef.current.play().catch(() => {
          // 处理播放失败的情况
          setIsPlaying(false)
        })
      }
    }
  }, [currentSong, playlist])

  if (!isVisible) {
    return (
      <button
        onClick={() => setIsVisible(true)}
        className="fixed bottom-4 right-4 bg-pink-500 text-white p-3 rounded-full shadow-lg hover:bg-pink-600 transition-colors z-50"
      >
        🎵
      </button>
    )
  }

  if (playlist.length === 0) {
    return null
  }

  return (
    <div className="fixed bottom-4 right-4 bg-white/90 backdrop-blur-sm rounded-2xl shadow-xl p-4 z-50 w-80">
      <audio
        ref={audioRef}
        onEnded={nextSong}
        onPlay={() => setIsPlaying(true)}
        onPause={() => setIsPlaying(false)}
      />
      
      <div className="flex items-center justify-between mb-3">
        <h3 className="font-semibold text-gray-800 text-sm">🎶 我们的音乐</h3>
        <div className="flex items-center space-x-2">
          <button
            onClick={() => setShowPlaylist(!showPlaylist)}
            className="text-gray-400 hover:text-gray-600 text-sm"
          >
            📋
          </button>
          <button
            onClick={() => setIsVisible(false)}
            className="text-gray-400 hover:text-gray-600 text-sm"
          >
            ✕
          </button>
        </div>
      </div>

      {showPlaylist ? (
        <div className="mb-3 max-h-40 overflow-y-auto">
          <h4 className="text-sm font-medium text-gray-700 mb-2">播放列表</h4>
          <div className="space-y-2">
            {playlist.map((song, index) => (
              <div
                key={song.id}
                className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
                  index === currentSong ? 'bg-pink-100' : 'hover:bg-gray-100'
                }`}
                onClick={() => selectSong(index)}
              >
                <div className="flex-1 min-w-0">
                  <p className="text-xs font-medium text-gray-700 truncate">{song.title}</p>
                  <p className="text-xs text-gray-500 truncate">{song.artist}</p>
                </div>
                <button
                  onClick={(e) => {
                    e.stopPropagation()
                    removeSong(song.id)
                  }}
                  className="text-red-400 hover:text-red-600 text-xs ml-2"
                >
                  🗑️
                </button>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="mb-3">
          <h4 className="font-medium text-gray-700 text-sm truncate">
            {playlist[currentSong]?.title || ''}
          </h4>
          <p className="text-gray-500 text-xs truncate">
            {playlist[currentSong]?.artist || ''}
          </p>
          {playlist[currentSong]?.description && (
            <p className="text-gray-400 text-xs mt-1 truncate">
              {playlist[currentSong].description}
            </p>
          )}
        </div>
      )}

      <div className="flex items-center justify-center space-x-4 mb-3">
        <button
          onClick={prevSong}
          className="text-gray-600 hover:text-pink-500 transition-colors"
          disabled={playlist.length <= 1}
        >
          ⏮️
        </button>
        <button
          onClick={togglePlay}
          className="bg-pink-500 text-white p-2 rounded-full hover:bg-pink-600 transition-colors"
        >
          {isPlaying ? '⏸️' : '▶️'}
        </button>
        <button
          onClick={nextSong}
          className="text-gray-600 hover:text-pink-500 transition-colors"
          disabled={playlist.length <= 1}
        >
          ⏭️
        </button>
      </div>

      <div className="flex items-center space-x-2">
        <span className="text-xs text-gray-500">🔊</span>
        <input
          type="range"
          min="0"
          max="1"
          step="0.1"
          value={volume}
          onChange={(e) => setVolume(parseFloat(e.target.value))}
          className="flex-1 h-1 bg-gray-200 rounded-lg appearance-none cursor-pointer"
        />
      </div>

      <div className="mt-2 text-center">
        <p className="text-xs text-gray-400">
          播放我们特别的回忆 💕
        </p>
      </div>
    </div>
  )
}
